package cn.tedu.user.management.controller;

import cn.tedu.rtms.commons.consts.HttpConsts;
import cn.tedu.rtms.commons.pojo.vo.PageData;
import cn.tedu.rtms.commons.security.LoginPrincipal;
import cn.tedu.rtms.commons.web.JsonResult;
import cn.tedu.user.management.pojo.dto.UserLoginInfoDTO;
import cn.tedu.user.management.pojo.param.*;
import cn.tedu.user.management.pojo.vo.*;
import cn.tedu.user.management.service.IUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 处理用户相关请求的控制器
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/users")
@Validated
@Api(tags = "01. 用户管理模块")
public class UserController {

    @Autowired
    private IUserService userService;

    public UserController() {
        log.debug("创建控制器类对象：UserController");
    }

    // http://localhost:9250/users/login
    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult<UserLoginInfoDTO> login(UserLoginInfoParam userLoginInfoParam, @ApiIgnore HttpServletRequest request) {
        log.debug("开始处理【用户登录】的请求，参数：{}", userLoginInfoParam);
        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader(HttpConsts.HEADER_USER_AGENT);
        UserLoginInfoDTO loginInfo = userService.login(userLoginInfoParam, remoteAddr, userAgent);
        log.debug("即将响应：{}", loginInfo);
        return JsonResult.ok(loginInfo);
    }

    // http://localhost:9250/users/logout
    @PostMapping("/logout")
    @ApiOperation("用户退出登录")
    @ApiOperationSupport(order = 11)
    public JsonResult<Void> logout(@RequestHeader(HttpConsts.HEADER_AUTHORIZATION) String jwt) {
        log.debug("开始处理【用户退出登录】的请求，参数：{}", jwt);
        userService.logout(jwt);
        return JsonResult.ok();
    }

    // http://localhost:9250/users/reg
    @PostMapping("/reg")
    @ApiOperation("员工注册")
    @ApiOperationSupport(order = 100)
    public JsonResult<Void> reg(@Valid UserAddNewParam userAddNewParam) {
        log.debug("开始处理【用户注册】的请求，参数：{}", userAddNewParam);
        userService.addNew(userAddNewParam, 0);
        return JsonResult.ok();
    }

    // http://localhost:9250/users/add-new
    @PostMapping("/add-new")
    @PreAuthorize("hasAuthority('/users/add-new')")
    @ApiOperation("添加员工")
    @ApiOperationSupport(order = 120)
    public JsonResult<Void> add(@Valid UserAddNewParam userAddNewParam) {
        log.debug("开始处理【管理员添加】的请求，参数：{}", userAddNewParam);
        userService.addNew(userAddNewParam, 1);
        return JsonResult.ok();
    }

    // http://localhost:9250/users/9527/delete
    @PostMapping("/{id:[0-9]+}/delete")
    @PreAuthorize("hasAuthority('/users/delete')")
    @ApiOperation("根据ID删除用户")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult<Void> delete(@PathVariable Long id, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【根据ID删除用户】的请求，参数：{}", id);
        log.debug("当事人：{}", loginPrincipal);
        userService.delete(id, loginPrincipal.getId());
        return JsonResult.ok();
    }


    // http://localhost:9250/users/9527/enable
    @PostMapping("/{id:[0-9]+}/enable")
    @PreAuthorize("hasAuthority('/users/enable')")
    @ApiOperation("启用用户")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult<Void> setEnable(@PathVariable Long id) {
        log.debug("开始处理【启用用户】的请求，参数：{}", id);
        userService.setEnable(id);
        return JsonResult.ok();
    }

    // http://localhost:9250/users/enableAll
    @PostMapping("/enableAll")
    @PreAuthorize("hasAuthority('/users/enableAll')")
    @ApiOperation("一键启用")
    public JsonResult<Void> setEnableAll() {
        log.debug("开始处理【一键启用】的请求");
        userService.setEnableAll();
        return JsonResult.ok();
    }

    // http://localhost:9250/users/9527/disable
    @PostMapping("/{id:[0-9]+}/disable")
    @PreAuthorize("hasAuthority('/users/disable')")
    @ApiOperation("禁用用户")
    @ApiOperationSupport(order = 320)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult<Void> setDisable(@PathVariable Long id, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【禁用用户】的请求，参数：{}", id);
        log.debug("当事人：{}", loginPrincipal);
        userService.setDisable(id, loginPrincipal.getId());
        return JsonResult.ok();
    }


    // http://localhost:9250/users/9527/resetPassword
    @PostMapping("/{id:[0-9]+}/resetPassword")
    @PreAuthorize("hasAuthority('/users/resetPassword')")
    @ApiOperation("根据ID重置密码")
    @ApiOperationSupport(order = 330)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult<Void> resetPassword(@PathVariable Long id, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【根据ID重置密码】的请求，参数：{}", id);
        log.debug("当事人：{}", loginPrincipal);
        userService.resetPassword(id, loginPrincipal.getId());
        return JsonResult.ok();
    }

    // http://localhost:9250/users
    @GetMapping("")
    @ApiOperation("查询用户列表")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", dataType = "long")
    })
    public JsonResult<PageData<UserListItemVO>> list(Integer page) {
        log.debug("开始处理【查询用户列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<UserListItemVO> pageData = userService.list(pageNum);
        return JsonResult.ok(pageData);
    }

    // http://localhost:9250/users/regAuthorize
    @GetMapping("/regAuthorize")
    @ApiOperation("查询注册列表")
    @ApiOperationSupport(order = 430)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", dataType = "long")
    })
    public JsonResult<PageData<UserListItemVO>> regList(Integer page) {
        log.debug("开始处理【查询注册列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<UserListItemVO> pageData = userService.regList(pageNum);
        return JsonResult.ok(pageData);
    }

    // http://localhost:9250/targetUserList
    @PostMapping("/targetUserList")
    @ApiOperation("根据关键字查询员工列表")
    @ApiOperationSupport(order = 440)
    public JsonResult<List<UserListItemVO>> list(TargetUserParam targetUserParam) {
        log.debug("开始处理【查询目标员工列表】的请求，目标信息：{}", targetUserParam);
        List<UserListItemVO> list = userService.selectByKeywords(targetUserParam.getKeywords());
        return JsonResult.ok(list);
    }

    // http://localhost:9250/users/ownInfo
    @GetMapping("/ownInfo")
    @ApiOperation("查询个人信息表")
    @ApiOperationSupport(order = 450)
    public JsonResult<UserOwnInfoVO> userOwnInfo(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始查询【当前账号资料】,当事人：{}", loginPrincipal);
        UserOwnInfoVO userOwnInfo = userService.userOwnInfo(loginPrincipal.getId());
        return JsonResult.ok(userOwnInfo);
    }

    // http://localhost:9250/users/9527/update
    @PostMapping("/{id:[0-9]+}/update")
    @PreAuthorize("hasAuthority('/users/update')")
    @ApiOperation("修改员工信息")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工ID", required = true, dataType = "long")
    })
    public JsonResult<Void> updateInfoById(@PathVariable @Range(min = 1, message = "请提交有效的员工ID值！") Long id,
                                           @Valid UserUpdateInfoParam userUpdateInfoParam,
                                           @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【修改员工信息】的请求，ID：{}，新数据：{}", id, userUpdateInfoParam);
        log.debug("开始查询【当前账号资料】,当事人：{}", loginPrincipal);
        userService.updateInfoById(id, userUpdateInfoParam, loginPrincipal.getId());
        return JsonResult.ok();
    }

    // http://localhost:9250/updatePassword
    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    @ApiOperationSupport(order = 340)
    public JsonResult<Void> updatePassword(@Valid UserPasswordParam userPasswordParam,
                                           @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【修改密码】的请求，目标信息：{}", userPasswordParam);
        log.debug("当事人：{}", loginPrincipal);
        userService.updatePassword(loginPrincipal.getId(), userPasswordParam);
        return JsonResult.ok();
    }

    // http://localhost:9250/updateOwn
    @PostMapping("/updateOwn")
    @ApiOperation("修改个人资料")
    @ApiOperationSupport(order = 360)
    public JsonResult<Void> updateOwnInfo(@Valid UserUpdateInfoParam userUpdateInfoParam,
                                          @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【修改个人资料】的请求，目标信息：{}", userUpdateInfoParam);
        log.debug("当事人：{}", loginPrincipal);
        userService.updateInfoById(loginPrincipal.getId(), userUpdateInfoParam, 0L);
        return JsonResult.ok();
    }

    // http://localhost:9250/users/9527
    @GetMapping("/{id:[0-9]+}")
    @ApiOperation("根据ID查询员工信息")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工ID", required = true, dataType = "long")
    })
    public JsonResult<UserStandardVO> getStandardById(
            @PathVariable @Range(min = 1, message = "请提交有效的员工ID值！") Long id) {
        log.debug("开始处理【根据ID查询员工信息】的请求，参数：{}", id);
        UserStandardVO queryResult = userService.getStandardById(id);
        return JsonResult.ok(queryResult);
    }

    // http://localhost:9250/users/9527/userRole
    @GetMapping("/{id:[0-9]+}/userRole")
    @ApiOperation("根据ID查询员工角色")
    @ApiOperationSupport(order = 460)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工ID", required = true, dataType = "long")
    })
    public JsonResult<UserRoleStandardVO> getUserRoleById(
            @PathVariable @Range(min = 1, message = "请提交有效的员工ID值！") Long id) {
        log.debug("开始处理【根据ID查询员工角色信息】的请求，参数：{}", id);
        UserRoleStandardVO queryResult = userService.getUserRoleById(id);
        return JsonResult.ok(queryResult);
    }


    // http://localhost:9250/userList
    @GetMapping("/userList")
    @ApiOperation("查询员工列表")
    @ApiOperationSupport(order = 470)
    public JsonResult<List<UserListVO>> userList() {
        log.debug("开始处理【查询员工列表】的请求");
        List<UserListVO> list = userService.selectUserList();
        return JsonResult.ok(list);
    }
}